import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_rider/kit/app_update_kit.dart';
import 'package:flutter_rider/main/page/debug_page.dart';
import 'package:flutter_rider/main/page/print_setting_page.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/module/login/page/login_page.dart';
import 'package:flutter_rider/module/mine/mine_router.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/utils/cacheManager.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/app.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:common_utils/common_utils.dart';

class SettingPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SettingPageState();
  }
}

class SettingPageState extends State<SettingPage> {
  var _version = "1.0";
  var _clickCount = 0;
  var _clickCount2 = 0;
  var _cacheSting = "0MB";
  Timer? _timer;
  Timer? _timer2;

  getAppInfo() async {
    var pkgInfo = await PackageInfo.fromPlatform();
    setState(() {
      _version = pkgInfo.version;
    });
  }

  @override
  void initState() {
    super.initState();
    getAppInfo();
    getAppCache();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: UIColor.color_main,
      child: Column(
        children: [
          _renderTitle(),
          Container(height: 1, color: Colors.black12),
          12.hspace,
          _renderOrentaion(),
          12.hspace,
          _renderVersion(),
          12.hspace,
          _renderDebug(),
          12.hspace,
          // _renderClearCeche(),
          // 12.hspace,
          const Spacer(),
          _renderLogout(),
          20.hspace,
          //_renderDebug(),
        ],
      ).onTap(() async {
        _clickCount2 += 1;
        Log.i("${_clickCount},${_clickCount2}");
        if (_clickCount >= 5 && _clickCount2 >= 5) {
          Tip.show("debug模式开启");
          _clickCount2 = 0;

          var sp = await SharedPreferences.getInstance();
          sp.setBool("debug_mode", true);
          App.isDebugMode = true;
          setState(() {});
        }
        _timer2 ??= Timer(const Duration(seconds: 4), () {
          _clickCount2 = 0;
          _timer2 = null;
        });
      }),
    );
  }

  Widget _renderTitle() {
    return GestureDetector(
      child: Container(
        color: UIColor.color_content,
        width: double.infinity,
        height: MediaQuery.of(context).padding.top + 44.rpx,
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: Center(child: UText.get("设置", Colors.black, 16.rpx, fw: FontWeight.w600)),
      ),
      onTap: () {
        _clickCount += 1;
        Log.i("${_clickCount},${_clickCount2}");
        _timer ??= Timer(const Duration(seconds: 5), () {
          _clickCount = 0;
          _timer = null;
        });
      },
    );
  }

  Widget _renderOrentaion() {
    return GestureDetector(
      child: Container(
        color: UIColor.color_content,
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Row(
          children: [
            UText.getMainText("屏幕方向"),
            const Spacer(),
            UText.getMainText(App.isLandscape ? "横屏" : "竖屏"),
            Icon(Icons.navigate_next, size: 16.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        var tip = App.isLandscape ? "确定切换屏幕方向为竖屏?" : "确定切换屏幕方向为横屏?";
        CustomAlertDialog.show(context, content: tip, onConfirm: () {
          App.setScreenLandscape(!App.isLandscape);
          setState(() {

          });
        });
      },
    );
  }

  Widget _renderVersion() {
    return GestureDetector(
      child: Container(
        color: UIColor.color_content,
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Row(
          children: [
            UText.getMainText("版本"),
            const Spacer(),
            UText.getMainText("v${_version}"),
            Icon(Icons.navigate_next, size: 16.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        AppUpdateKit.instance.check(context, true);
      },
    );
  }

  Widget _renderDebug() {
    if (!App.isDebugMode) {
      return 0.hspace;
    }
    return GestureDetector(
      child: Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        color: UIColor.color_content,
        child: Row(
          children: [
            UText.getMainText("debug"),
            const Spacer(),
            Icon(Icons.navigate_next, size: 16.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        OpenUtils.open(context, DebugPage());
      },
    );
  }

  Widget _renderClearCeche() {
    return GestureDetector(
      child: Container(
        color: UIColor.color_content,
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Row(
          children: [
            UText.getMainText("清除缓存"),
            const Spacer(),
            UText.getMainText("${_cacheSting}"),
          ],
        ),
      ),
      onTap: () {
        clearAllCache();
        Tip.show("缓存已清空");
        setState(() {
          _cacheSting = "0MB";
        });
      },
    );
  }

  Widget _renderLogout() {
    return Padding(
      child: UText.getBkButton(
        "退出登录",
        16.rpx,
        width: double.infinity,
        height: 48.rpx,
        bkColor: UIColor.color_primary,
        radius: 12.rpx,
        onPressed: () {
          _onClickLogout();
        },
      ),
      padding: EdgeInsets.symmetric(horizontal: 12.rpx),
    );
  }

  _onClickLogout() {
    CustomAlertDialog.show(context, content: "确定退出登录?", onConfirm: () {
      Api.logout();
      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
        builder: (context) {
          return LoginPage();
        },
      ), (route) => false);
    });
  }

  Widget _renderPrinter() {
    return GestureDetector(
      child: Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        decoration: const BoxDecoration(color: UIColor.color_content, boxShadow: [
          BoxShadow(color: Colors.black12, offset: Offset(-0.1, -0.1), blurRadius: 0.1),
          BoxShadow(color: Colors.black12, offset: Offset(0.1, 0.1), blurRadius: 0.1),
        ]),
        child: Row(
          children: [
            UText.getMainText("打印机设置"),
            const Spacer(),
            Icon(Icons.navigate_next, size: 16.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        OpenUtils.open(context, PrintSettingPage());
      },
    );
  }

  // 获取缓存的大小
  void getAppCache() {
    CacheUtil.loadApplicationCache().then((value) {
      // 获取到缓存大小
      _cacheSting = value == 0.0?"0MB":CacheUtil.formatSize(value);
    });
  }

  //清除所有缓存
  Future<void> clearAllCache() async {
    // 获取缓存
    Directory directory = await getApplicationDocumentsDirectory();
    //清楚缓存并重新获取缓存大小
    CacheUtil.delDir(directory).then((value) => getAppCache());
    _cacheSting = "0MB";
  }
}